package net.lesscoding.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.AdaptiveRecvByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import net.lesscoding.common.Const;

/**
 * @author eleven
 * @date 2024/10/29 14:42
 * @apiNote
 */
public class HelloWorldServer {
    public static void main(String[] args) {
        HelloWorldServer helloWorldServer = new HelloWorldServer();
        helloWorldServer.start();
    }

    void start() {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel channel) throws Exception {
                            channel.pipeline()
                                    .addLast(new LineBasedFrameDecoder(1024 * 1024))
                                    .addLast(new LoggingHandler(LogLevel.DEBUG));
                        }
                    });
            // 调整系统的接收缓冲区（滑动窗口）
            //serverBootstrap.option(ChannelOption.SO_RCVBUF, 16);
            // 调整netty的缓冲区大小 16
            serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(16, 16, 16));
            ChannelFuture future = serverBootstrap.bind(Const.PORT).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
